<template>
  <el-cascader
    v-model="currentValue"
    :options="deptOptions"
    :props="cascaderProps"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :filterable="filterable"
    :size="size"
    :style="{ width: width }"
    @change="handleChange"
    @clear="handleClear"
  />
</template>

<script>
import { listDept } from "@/api/system/dept";
import { handleTree } from "@/utils/ruoyi";

export default {
  name: "DeptSelect",
  props: {
    value: {
      type: [String, Number, Array],
      default: null
    },
    placeholder: {
      type: String,
      default: "请选择部门"
    },
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    filterable: {
      type: Boolean,
      default: true
    },
    checkStrictly: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: ""
    },
    width: {
      type: String,
      default: "100%"
    },
    // 是否只显示叶子节点
    onlyLeaf: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      deptOptions: [],
      loading: false
    };
  },
  computed: {
    currentValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      }
    },
    cascaderProps() {
      return {
        value: 'deptId',
        label: 'deptName',
        children: 'children',
        checkStrictly: this.checkStrictly,
        leaf: this.onlyLeaf ? 'leaf' : null
      };
    }
  },
  created() {
    this.getDeptList();
  },
  methods: {
    /** 获取部门列表 */
    getDeptList() {
      this.loading = true;
      listDept().then(response => {
        const deptList = response.data || [];
        
        // 筛选parent_id > 100的部门（排除顶级公司节点）
        const filteredDepts = deptList.filter(dept => dept.parentId > 100);
        
        // 构建树形结构
        this.deptOptions = this.handleTree(filteredDepts, 'deptId', 'parentId');
        
        // 如果只显示叶子节点，需要标记叶子节点
        if (this.onlyLeaf) {
          this.markLeafNodes(this.deptOptions);
        }
        
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 构建树形结构 */
    handleTree(data, id, parentId, children) {
      return handleTree(data, id, parentId, children);
    },
    /** 标记叶子节点 */
    markLeafNodes(nodes) {
      nodes.forEach(node => {
        if (!node.children || node.children.length === 0) {
          node.leaf = true;
        } else {
          this.markLeafNodes(node.children);
        }
      });
    },
    /** 选择变化 */
    handleChange(value) {
      this.$emit('input', value);
      this.$emit('change', value);
      
      // 查找选中的部门信息
      if (value && value.length > 0) {
        const selectedDept = this.findDeptById(this.deptOptions, value[value.length - 1]);
        this.$emit('dept-change', selectedDept);
      } else {
        this.$emit('dept-change', null);
      }
    },
    /** 清空选择 */
    handleClear() {
      this.$emit('input', null);
      this.$emit('change', null);
      this.$emit('clear');
      this.$emit('dept-change', null);
    },
    /** 递归查找部门 */
    findDeptById(nodes, deptId) {
      for (let node of nodes) {
        if (node.deptId === deptId) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = this.findDeptById(node.children, deptId);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    /** 刷新数据 */
    refresh() {
      this.getDeptList();
    }
  }
};
</script>

<style scoped>
</style> 